<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="formVisible = true">添加</el-button>
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="名称" value="1"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok"/>
      </div>
    </div>
    <el-table stripe style="width: 100%"  border fit highlight-current-row ref="tableDataRef" :data="tableData" :key="key">
      <el-table-column v-if="colData[0].istrue" min-width="50" align="center" prop="id" label="ID"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="50" align="center" prop="admin_name" label="创建者"></el-table-column>
      <el-table-column v-if="colData[3].istrue" min-width="50" align="center" prop="name" label="名称"></el-table-column>
      <el-table-column v-if="colData[4].istrue" min-width="60" align="center" prop="is_file" label="是否带附件"></el-table-column>
      <el-table-column v-if="colData[5].istrue"  min-width="100" align="center" prop="batch" label="分发批次">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.batch" :key="item.id" style="margin: 0;padding: 0">{{item.batch}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[6].istrue" min-width="80" align="center" prop="childAdmin" label="分发子账号">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.operates" :key="item.id"  style="margin: 0;padding: 0">{{item.username}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[7].istrue" min-width="140" align="center" prop="send_time" label="创建时间">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column v-if="colData[8].istrue" min-width="50" align="center" prop="is_need" label="是否要确认">
        <template slot-scope="scope">
          <span v-show="scope.row.is_need==1">是</span>
          <span v-show="scope.row.is_need==-1">否</span>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[9].istrue" min-width="50" align="center" prop="allSnNum"  label="应确认人数">
        <template slot-scope="scope">
          <p style="color: #0079ff" @click="openAllSn(scope.row.id)">{{scope.row.allSnNum}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[10].istrue" min-width="50" align="center" prop="read_sn_num"  label="已确认人数">
        <template slot-scope="scope">
          <p style="color: #0079ff" @click="openReadSn(scope.row.id)">{{scope.row.read_sn_num}}</p>
        </template>
      </el-table-column>
      <el-table-column v-if="colData[11].istrue" min-width="50" align="center" prop="noReadSn"  label="待确认人数">
        <template slot-scope="scope">
          <p style="color: #0079ff" @click="openNoReadSn(scope.row.id)">{{scope.row.noReadSn}}</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="openEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="delNotice(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination :current-page.sync="listQuery.startSize" background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
                     layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>

    <el-dialog title="待确认人数" :visible.sync="allReadSnVisible">
      <el-table :data="allReadSnData">
        <el-table-column property="value" align="center" label="SN" min-width="150"></el-table-column>
        <el-table-column property="batch" align="center" label="批次" ></el-table-column>
        <el-table-column property="classlevel" align="center" label="班级"></el-table-column>
        <el-table-column property="sno" align="center" label="学号" ></el-table-column>
        <el-table-column property="realname" align="center" label="姓名" ></el-table-column>
        <el-table-column property="phone" align="center" label="监护人1"></el-table-column>
        <el-table-column property="phone_two" align="center" label="监护人2"></el-table-column>
      </el-table>
      <div class="paging">
        <el-pagination :current-page.sync="allReadQuery.startSize" background @size-change="allReadSizeChange"
                       @current-change="allReadCurrentChange" :page-sizes="[10, 50, 100, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="allReadTotal" :page-size="allReadQuery.pageSize">
        </el-pagination>
      </div>
    </el-dialog>

    <el-dialog title="已确认人数" :visible.sync="readSnVisible" width="70%">
      <el-table :data="readSnData">
        <el-table-column property="sn" align="center" label="SN" min-width="150"></el-table-column>
        <el-table-column property="batch" align="center" label="批次" ></el-table-column>
        <el-table-column property="classlevel" align="center" label="班级"></el-table-column>
        <el-table-column property="sno" align="center" label="学号" ></el-table-column>
        <el-table-column property="realname" align="center" label="姓名" ></el-table-column>
        <el-table-column property="phone" align="center" label="监护人1"></el-table-column>
        <el-table-column property="create_time" align="center" label="确认时间" min-width="150">
          <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" align="center" v-if="false">
          <template slot-scope="scope">
            <el-row>
              <el-button v-if="scope.row.is_confirm==-1" size="mini" type="primary" @click="confirmNotice(scope.row.id)">待确认</el-button>
              <el-button v-else size="mini" type="info" disabled>已确认</el-button>
              <el-button size="mini" @click="openEdit(scope.row.feedback_content)">查看</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <div class="paging">
        <el-pagination :current-page.sync="hasReadQuery.startSize" background @size-change="hasReadSizeChange"
                       @current-change="hasReadCurrentChange" :page-sizes="[10, 50, 100, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="hasReadTotal" :page-size="hasReadQuery.pageSize">
        </el-pagination>
      </div>
    </el-dialog>

    <el-dialog title="待确认人数" :visible.sync="noReadSnVisible">
      <el-table :data="noReadSnData">
        <el-table-column property="value" align="center" label="SN" min-width="150"></el-table-column>
        <el-table-column property="batch" align="center" label="批次" ></el-table-column>
        <el-table-column property="classlevel" align="center" label="班级"></el-table-column>
        <el-table-column property="sno" align="center" label="学号" ></el-table-column>
        <el-table-column property="realname" align="center" label="姓名" ></el-table-column>
        <el-table-column property="phone" align="center" label="监护人1"></el-table-column>
        <el-table-column property="phone_two" align="center" label="监护人2"></el-table-column>
      </el-table>
      <div class="paging">
        <el-pagination :current-page.sync="noReadQuery.startSize" background @size-change="noReadSizeChange"
                       @current-change="noReadCurrentChange" :page-sizes="[10, 50, 100, 200]"
                       layout="total, sizes, prev, pager, next, jumper" :total="noReadTotal" :page-size="noReadQuery.pageSize">
        </el-pagination>
      </div>
    </el-dialog>


    <!-- 添加弹窗 -->
    <el-dialog :title="editSubjects== true ? '编辑通知': '添加通知' " :visible.sync="formVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="40%" @close="addFormclose">
      <el-form :model="addForm"  ref="ruleForm" :rules="rules" class="diolog_adapt" style="width: 600px" >
        <el-form-item label="名称:" label-width="120px" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入名称" maxlength="60"></el-input>
        </el-form-item>
        <el-form-item label="内容:" label-width="120px" prop="content">
          <el-input v-model="addForm.content" placeholder="请输入内容" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="文件上传:" label-width="120px" prop="fileList">
          <div class="flex felx_align">
            <el-upload class="upload-demo" action="#" id="file" :auto-upload="false" :show-file-list="true" multiple :file-list="addForm.fileList" :on-change="contentUpload" :on-remove="handleRemove">
              <el-button size="small" type="primary"><span>文件上传</span></el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="是否需确认:" label-width="120px" prop="is_need">
          <el-radio-group v-model="addForm.is_need">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="-1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分发方式:" label-width="120px" prop="send_type" >
          <el-radio-group v-model="addForm.send_type" @input="toSetBatchAdmin">
            <el-radio :label="1">批次</el-radio>
            <el-radio :label="2">子账号</el-radio>
            <el-radio :label="3">批次和子账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="批次:" v-show="addForm.send_type==1 || addForm.send_type==3" label-width="120px">
          <el-select v-model="addForm.batch"  multiple filterable placeholder="请选择批次">
            <el-option
              v-for="item in batchArr"
              :key="item.id"
              :label="item.batch"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子账号:" v-show="addForm.send_type==2 || addForm.send_type==3" label-width="120px">
          <el-select v-model="addForm.child_admin"  multiple placeholder="请选择子账号">
            <el-option
              v-for="item in childrenOption"
              :key="item.id"
              :label="item.username"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="确认截至时间:" label-width="120px" v-show="!isVisible" prop="feedback_end_time">
          <el-date-picker
            v-model="addForm.feedback_end_time"
            type="datetime"
            placeholder="选择日期时间"
            align="center"
            value-format="timestamp"
            :default-time="'23:59:59'"
           >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="确认方式:" label-width="120px" v-show="!isVisible" prop="feedback_type">
          <el-select v-model="addForm.feedback_type" placeholder="请选择">
            <el-option
              v-for="item in feedBackOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false" size="mini" round>取 消</el-button>
        <el-button v-if="editSubjects" type="primary" size="mini" round @click="editNotice('ruleForm')">确 定
        </el-button>
        <el-button v-else type="primary" @click="addNotice('ruleForm')" size="mini" round>确定</el-button>
      </div>
    </el-dialog>
    <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
  </div>

</template>

<script>
  import objectable from "@/utils/objectable.js";
  import dynamicTable from "@/components/DynamicTable";
  import deleteDialog from "@/components/deleteDialog";
  import tableMini from '@/utils/tableMini.js'
  import {
    getChildAdmin,
    confirmNotice,
    addSelfNotice,
    querySelfNotice,
    editSelfNotice,
    delSelfNotice,
    getAllReadNotice,
    getNoReadNotice,
    getSnReadNotice,
  } from "@/api/launcherMade";
  import {ossFile} from "@/utils/ossUpload";
  import {getBatchTwo} from "@/api/equipment";

  export default {
    mixins: [tableMini],
    components: {dynamicTable, deleteDialog},
    data() {
      return {
        key: 1,
        colData: [], //动态控制table
        checkboxVal: ["ID", "创建者", "发布类型", "名称", "是否带附件", "批次", "子账号", "创建日期", "是否要确认", "应确认人数", "已确认人数", "待确认人数"],
        searchTable: "",
        select: "", //搜索条件
        tableData: [],
        listQuery: {
          startSize: 1,
          pageSize: 10,
          userId: localStorage.getItem("ID"),
        },
        hasReadQuery: {
          startSize: 1,
          pageSize: 10,
          id: undefined
        },
        noReadQuery: {
          startSize: 1,
          pageSize: 10,
          id: undefined
        },
        allReadQuery: {
          startSize: 1,
          pageSize: 10,
          id: undefined
        },
        addForm: {
          name: '',
          content: '',
          fileList:[],
          is_need: 1, //是否需要确认 1:是 -1:否
          feedback_end_time: '', //确认截至时间
          feedback_type: 1,      //1.文件 2.文件+附件
          send_type: '',
          batch: [],
          child_admin: [],
        },
        formVisible: false,
        rules: {
          name: [{required: true, message: '请输入名称', trigger: 'blur'}],
          content: [{required: true, message: '请输入内容', trigger: 'blur'}],
          is_need: [{ required: true, message: '请选择是否确认', trigger: 'change' }],
          send_type: [{ required: true, message: '请选择分发方式', trigger: 'change' }],
        },
        editSubjects: false,
        deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
        batchArr: [],
        childrenOption: [],  //子账号可选框
        feedBackOptions: [{label:'文字', value:1}, {label: '文字+附件', value: 2}],
        isVisible:false,
        fileList: [],
        readSnVisible: false,
        noReadSnVisible: false,
        allReadSnVisible:false,
        readSnData: [],
        noReadSnData: [],
        allReadSnData: [],
        hasReadTotal: 0,
        noReadTotal: 0,
        allReadTotal: 0,
      }
    },
    created() {
      this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
      this.getSelfNoticeTableData()
      this.getBatchTwo()
      this.getChildAdmin()
    },
    methods: {
      Refresh() {
        this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), name: undefined,  create_time: undefined}
        this.getSelfNoticeTableData()
      },

      openReadSn(id) {
        this.readSnVisible=true
        this.hasReadQuery.id = id
        this.getSnReadHomeworkData()
      },
      getSnReadHomeworkData() {
        getSnReadNotice(this.hasReadQuery).then(res => {
          this.readSnData = res.data
          this.hasReadTotal = res.total
        }).catch(err => {
          this.readSnData = []
          this.hasReadTotal = 0
        })
      },
      openNoReadSn(id) {
        this.noReadSnVisible=true
        this.noReadQuery.id = id
        this.getNoReadNotice()
      },
      getNoReadNotice() {
        getNoReadNotice(this.noReadQuery).then(res => {
          this.noReadSnData = res.data
          this.noReadTotal = res.total
        }).catch(err => {
          this.noReadSnData = []
          this.noReadTotal = 0
        })
      },
      openAllSn(id) {
        this.allReadSnVisible=true
        this.allReadQuery.id=id
        this.getAllReadNoticeData()
      },
      getAllReadNoticeData() {
        getAllReadNotice(this.allReadQuery).then(res => {
          this.allReadSnData = res.data
          this.allReadTotal = res.total
        }).catch(err => {
          this.allReadSnData = []
          this.allReadTotal = 0
        })
      },
      confirmNotice(id) {
        this.$confirm('是否更改通知状态为已确认?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          let param = {
            userId: localStorage.getItem('ID'),
            last_ip: sessionStorage.getItem("Ip"),
            id: id
          }
          confirmNotice(param).then(res => {
           this.$message.success(res.msg)
           this.getSnReadHomeworkData()
         }).catch(err => {

         })
        }).catch(() => {
        });
      },

      toSetBatchAdmin(event) {
        switch (event) {
          case 1:
            this.addForm.child_admin = [];
            break;
          case 2:
            this.addForm.batch = [];
            break;
        }
      },
      openEdit(content) {
        this.$alert(content, '查看通知内容', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      },
      //搜索,1:课程名称
      idnameSearch() {
        if (!this.select) return this.$message.warning("请先选择查询条件");
        this.listQuery.startSize = 1
        this.listQuery.pageSize = 10
        switch (this.select) {
          case '1':
            this.listQuery.name = this.searchTable
            this.getSelfNoticeTableData();
            break;
        }
      },
      getBatchTwo() {
        getBatchTwo({ userId: localStorage.getItem("ID") }).then(res => {
          this.batchArr = res.data
        }).catch(err => {
          this.batchArr = []
        })
      },
      getChildAdmin() {
        getChildAdmin({ userId: localStorage.getItem("ID") }).then(res => {
          this.childrenOption = res.data
        }).catch(err => {
          this.childrenOption = []
        })
      },
      openEdit(row) {
        this.formVisible = true
        this.editSubjects=true
        this.isVisible = row.notice_type === 3
        this.addForm = {
          id: row.id,
          name: row.name,
          content: row.content,
          fileList:row.file_list,
          is_need: row.is_need, //是否需要确认 1:是 -1:否
          feedback_type: row.feedback_type,      //1.文件 2.文件+附件
          send_type: row.send_type,
          feedback_end_time: row.feedback_end_time,
          batch: row.batchArr,
          child_admin: row.childAdmin,
        }
      },
      addNotice(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let addForm = JSON.parse(JSON.stringify(this.addForm))
            addForm.last_ip = sessionStorage.getItem("Ip")
            addForm.userId = localStorage.getItem("ID")
            addSelfNotice(addForm).then(res => {
              if(res.code==200){
                this.$message.success(res.msg)
                this.getSelfNoticeTableData()
              }
              this.formVisible = false
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      getSelfNoticeTableData() {
        querySelfNotice(this.listQuery).then(res => {
            this.tableData = res.data
            this.total = res.total
        }).catch(err => {
          this.tableData = []
          this.total = 0
        })
      },
      editNotice(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            let editForm = JSON.parse(JSON.stringify(this.addForm))
            editForm.last_ip = sessionStorage.getItem("Ip")
            editForm.userId = localStorage.getItem("ID")
            editSelfNotice(editForm).then(res => {
              this.$message.success(res.msg)
              this.formVisible = false
              this.getSelfNoticeTableData()
            }).catch(err => {
            })
          } else {
            return false;
          }
        });
      },
      delNotice(id) {
        this.deleteDialogs.show = true
        this.deleteDialogs.deleteId = id
      },
      //删除按钮事件
      deleteEvents() {
        let params = {
          userId: localStorage.getItem("ID"),
          last_ip: sessionStorage.getItem("Ip"),
          id: this.deleteDialogs.deleteId,
        }
        delSelfNotice(params).then(res => {
          if(res.code==200){
            this.$message.success(res.msg)
          }else{
            this.$message.error(res.msg)
          }
          this.getSelfNoticeTableData()
        }).catch(err => {
          console.log("请求失败", err)
        })
      },
      //分页
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getSelfNoticeTableData()
      },
      handleCurrentChange(val) {
        this.listQuery.startSize = val
        this.getSelfNoticeTableData()
      },
      hasReadSizeChange(val) {
        this.hasReadQuery.pageSize = val
        this.getSnReadHomeworkData()
      },
      hasReadCurrentChange(val) {
        this.hasReadQuery.startSize = val
        this.getSnReadHomeworkData()
      },
      noReadSizeChange(val) {
        this.noReadQuery.pageSize = val
        this.getNoReadNotice()
      },
      noReadCurrentChange(val) {
        this.noReadQuery.startSize = val
        this.getNoReadNotice()
      },
      allReadSizeChange(val) {
        this.allReadQuery.pageSize = val
        this.getAllReadNoticeData()
      },
      allReadCurrentChange(val) {
        this.allReadQuery.startSize = val
        this.getAllReadNoticeData()
      },
      //下拉动态table子组件
      alterCheckbok(key, conte) {
        this.key = key;
        this.colData.filter(i => {
          if (conte.indexOf(i.title) != -1) {
            i.istrue = false;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          } else {
            i.istrue = true;
            this.$nextTick(() => {
              this.$refs.tableDataRef.doLayout();
            });
          }
        });
      },
      //文件上传
      contentUpload(file, fileList) {
        ossFile(file.raw,file.name).then(ossUrl => {//文件上传
          this.addForm.fileList.push({name:file.name, url: ossUrl})
          this.$message.success("上传成功")
        }).catch(err => {
          this.$message.error("文件上传失败")
        })
      },
      handleRemove(file, fileList) {
        this.addForm.fileList = this.addForm.fileList.filter(item => {
          return item.name != file.name
        })
      },
      //编辑添加表单关闭事件
      addFormclose() {
        this.editSubjects=false
        this.$nextTick(() => {
          this.addForm = this.$options.data().addForm
        })
      },
    }
  }
</script>


